<?php defined( 'BASEPATH' ) or die( 'Restricted' );

/*
This code is copyright 2009-2011 by TMLA INC.  ALL RIGHTS RESERVED.
Please view license.txt in /tgsf_core/legal/license.txt or
http://tgWebSolutions.com/opensource/tgsf/license.txt
for complete licensing information.
*/


class linkTagModel extends tgsfBase
{
	//------------------------------------------------------------------------
	/**
	* creates a link to tag relationship
	*/
	public function insert( $ds )
	{
		if ( $this->exists( $ds ) )
		{
			return true;
		}

		return query::factory()
			->insert_into( 'link_tag' )
			->pt( ptINT )
			->insert_fields( 'link_tag_tag_id', 'link_tag_link_id' )
			->autoBind( $ds )
			->exec();
	}
	//------------------------------------------------------------------------
	/**
	*
	*/
	public function exists( $ds )
	{
		return query::factory()
			->count()
			->from( 'link_tag' )
			->where( 'link_tag_tag_id=:tag_id' )
			->bindValue( 'tag_id', $ds->link_tag_tag_id, ptINT )
			->where( 'link_tag_link_id = :link_id' )
			->bindValue( 'link_id', $ds->link_tag_link_id, ptINT )
			->exec()
			->fetchColumn(0) > 0;
	}
	//------------------------------------------------------------------------
	/**
	* returns the tag id for the given text
	* @param String The tag text
	*/
	public function delete( $ds )
	{
		if ( $this->exists( $ds->link_tag_tag_id ) )
		{
			return true;
		}

		return query::factory()
			->delete_from( 'tag' )
			->where( 'link_tag_tag_id = :link_tag_tag_id AND link_tag_link_id = :link_tag_link_id' )
			->bindValue( 'link_tag_tag_id', $ds->link_tag_tag_id, ptINT )
			->bindValue( 'link_tag_link_id', $ds->link_tag_link_id, ptINT )
			->exec();
	}
	//------------------------------------------------------------------------
	/**
	*
	*/
	public function fetchForLink( $id )
	{
		return query::factory()
			->select()
			->from( 'link_tag' )
			->join( 'tag', 'link_tag_tag_id = tag_id' )
			->where( 'link_tag_link_id = :link_id' )
			->bindValue( 'link_id', $id, ptINT )
			->dbDataSource();
	}
}

return new linkTagModel();
